// 建筑基类
class Building {
    constructor(x, y, type) {
        this.x = x;
        this.y = y;
        this.type = type;
        this.size = 40;
        this.isDestroyed = false;
        this.color = '#8B4513';
        
        // 建筑状态
        this.health = 1000;
        this.maxHealth = 1000;
        this.isInvulnerable = true; // 建筑不可破坏
        
        // 生产相关
        this.productionCooldown = 10000; // 10秒生产一个
        this.lastProductionTime = 0;
        this.maxMinions = 5; // 最大小兵数量
        this.currentMinions = 0;
        
        // 视觉效果
        this.animationFrame = 0;
        this.animationSpeed = 0.1;
        this.pulseEffect = 0;
    }
    
    // 更新建筑
    update(deltaTime) {
        if (this.isDestroyed) return;
        
        this.updateAnimation(deltaTime);
        this.updateProduction(deltaTime);
        this.updatePulseEffect(deltaTime);
    }
    
    // 更新动画
    updateAnimation(deltaTime) {
        this.animationFrame += this.animationSpeed * deltaTime;
        if (this.animationFrame >= 4) {
            this.animationFrame = 0;
        }
    }
    
    // 更新脉冲效果
    updatePulseEffect(deltaTime) {
        this.pulseEffect += deltaTime * 0.005;
        if (this.pulseEffect >= Math.PI * 2) {
            this.pulseEffect = 0;
        }
    }
    
    // 更新生产
    updateProduction(deltaTime) {
        const currentTime = Date.now();
        
        // 检查是否可以生产新的小兵
        if (currentTime - this.lastProductionTime >= this.productionCooldown && 
            this.currentMinions < this.maxMinions) {
            this.produceMinion();
            this.lastProductionTime = currentTime;
        }
    }
    
    // 生产小兵
    produceMinion() {
        if (!window.game || !window.game.minionManager) return;
        
        // 在建筑周围随机位置生成小兵
        const angle = Math.random() * Math.PI * 2;
        const distance = this.size + 20;
        const spawnX = this.x + Math.cos(angle) * distance;
        const spawnY = this.y + Math.sin(angle) * distance;
        
        // 确保生成位置在世界范围内
        const finalX = Utils.clamp(spawnX, this.size, GAME_CONFIG.WORLD_WIDTH - this.size);
        const finalY = Utils.clamp(spawnY, this.size, GAME_CONFIG.WORLD_HEIGHT - this.size);
        
        window.game.minionManager.addMinion(finalX, finalY);
        this.currentMinions++;
        
        // 显示生产效果
        if (window.game.effectManager) {
            window.game.effectManager.addEffect(this.x, this.y, 'spawn');
        }
        
        // 播放生产音效
        if (window.game.sounds && window.game.sounds.spawn) {
            window.game.soundGenerator.playSound(window.game.sounds.spawn);
        }
        
        console.log(`建筑生产了小兵！当前小兵数量: ${this.currentMinions}/${this.maxMinions}`);
    }
    
    // 受到伤害（建筑不可破坏）
    takeDamage(damage) {
        // 建筑不可破坏，忽略伤害
        return false;
    }
    
    // 渲染建筑
    render(ctx) {
        if (this.isDestroyed) return;
        
        ctx.save();
        
        // 绘制建筑主体
        ctx.fillStyle = this.color;
        ctx.fillRect(this.x - this.size/2, this.y - this.size/2, this.size, this.size);
        
        // 绘制建筑边框
        ctx.strokeStyle = '#FFFFFF';
        ctx.lineWidth = 2;
        ctx.strokeRect(this.x - this.size/2, this.y - this.size/2, this.size, this.size);
        
        // 绘制建筑标识
        ctx.fillStyle = '#FFD700';
        ctx.font = '12px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('🏠', this.x, this.y - 5);
        
        // 绘制生产进度条
        this.renderProductionProgress(ctx);
        
        // 绘制脉冲效果
        this.renderPulseEffect(ctx);
        
        // 绘制小兵数量指示器
        this.renderMinionCount(ctx);
        
        ctx.restore();
    }
    
    // 渲染生产进度条
    renderProductionProgress(ctx) {
        const currentTime = Date.now();
        const progress = Math.min(1, (currentTime - this.lastProductionTime) / this.productionCooldown);
        
        const barWidth = this.size;
        const barHeight = 4;
        const barX = this.x - barWidth/2;
        const barY = this.y + this.size/2 + 5;
        
        // 背景
        ctx.fillStyle = '#333333';
        ctx.fillRect(barX, barY, barWidth, barHeight);
        
        // 进度
        ctx.fillStyle = '#00FF00';
        ctx.fillRect(barX, barY, barWidth * progress, barHeight);
        
        // 边框
        ctx.strokeStyle = '#FFFFFF';
        ctx.lineWidth = 1;
        ctx.strokeRect(barX, barY, barWidth, barHeight);
    }
    
    // 渲染脉冲效果
    renderPulseEffect(ctx) {
        const pulseSize = this.size + Math.sin(this.pulseEffect) * 5;
        ctx.strokeStyle = '#00FF00';
        ctx.lineWidth = 2;
        ctx.globalAlpha = 0.5;
        ctx.strokeRect(this.x - pulseSize/2, this.y - pulseSize/2, pulseSize, pulseSize);
        ctx.globalAlpha = 1;
    }
    
    // 渲染小兵数量指示器
    renderMinionCount(ctx) {
        ctx.fillStyle = '#FFFFFF';
        ctx.font = '10px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(`${this.currentMinions}/${this.maxMinions}`, this.x, this.y + this.size/2 + 20);
    }
    
    // 检查与其他对象的碰撞
    collidesWith(other) {
        return Utils.rectCollision(
            this.x - this.size/2, this.y - this.size/2, this.size, this.size,
            other.x - (other.size || 0), other.y - (other.size || 0), 
            (other.size || 0) * 2, (other.size || 0) * 2
        );
    }
}

// 兵营类（生产小兵的建筑）
class Barracks extends Building {
    constructor(x, y) {
        super(x, y, 'barracks');
        this.color = '#8B4513';
        this.productionCooldown = 8000; // 8秒生产一个
        this.maxMinions = 8;
    }
    
    render(ctx) {
        super.render(ctx);
        
        // 绘制兵营特殊标识
        ctx.fillStyle = '#FFD700';
        ctx.font = '14px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('⚔️', this.x, this.y + 5);
    }
}

// 工厂类（生产更高级小兵的建筑）
class Factory extends Building {
    constructor(x, y) {
        super(x, y, 'factory');
        this.color = '#696969';
        this.productionCooldown = 15000; // 15秒生产一个
        this.maxMinions = 4;
    }
    
    // 生产更高级的小兵
    produceMinion() {
        if (!window.game || !window.game.minionManager) return;
        
        // 在建筑周围随机位置生成小兵
        const angle = Math.random() * Math.PI * 2;
        const distance = this.size + 20;
        const spawnX = this.x + Math.cos(angle) * distance;
        const spawnY = this.y + Math.sin(angle) * distance;
        
        // 确保生成位置在世界范围内
        const finalX = Utils.clamp(spawnX, this.size, GAME_CONFIG.WORLD_WIDTH - this.size);
        const finalY = Utils.clamp(spawnY, this.size, GAME_CONFIG.WORLD_HEIGHT - this.size);
        
        // 创建高级小兵（等级更高）
        const minion = window.game.minionManager.addMinion(finalX, finalY);
        if (minion) {
            minion.level = 3; // 工厂生产的小兵初始等级为3
            minion.maxHealth = 60;
            minion.health = 60;
            minion.damage = 25;
            minion.color = '#FFD700'; // 金色表示高级小兵
        }
        
        this.currentMinions++;
        
        // 显示生产效果
        if (window.game.effectManager) {
            window.game.effectManager.addEffect(this.x, this.y, 'spawn');
        }
        
        console.log(`工厂生产了高级小兵！当前小兵数量: ${this.currentMinions}/${this.maxMinions}`);
    }
    
    render(ctx) {
        super.render(ctx);
        
        // 绘制工厂特殊标识
        ctx.fillStyle = '#FFD700';
        ctx.font = '14px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('🏭', this.x, this.y + 5);
    }
}

// 建筑管理器
class BuildingManager {
    constructor() {
        this.buildings = [];
        this.buildingTypes = {
            BARRACKS: 'barracks',
            FACTORY: 'factory'
        };
    }
    
    // 添加建筑
    addBuilding(x, y, type) {
        let building;
        
        switch(type) {
            case this.buildingTypes.BARRACKS:
                building = new Barracks(x, y);
                break;
            case this.buildingTypes.FACTORY:
                building = new Factory(x, y);
                break;
            default:
                building = new Building(x, y, type);
        }
        
        this.buildings.push(building);
        console.log(`添加了建筑: ${type} 在位置 (${x}, ${y})`);
        
        return building;
    }
    
    // 更新所有建筑
    update(deltaTime) {
        this.buildings.forEach(building => {
            building.update(deltaTime);
        });
        
        // 更新小兵数量统计
        this.updateMinionCounts();
    }
    
    // 更新小兵数量统计
    updateMinionCounts() {
        if (!window.game || !window.game.minionManager) return;
        
        const actualMinionCount = window.game.minionManager.getMinionCount();
        
        // 更新所有建筑的小兵数量统计
        this.buildings.forEach(building => {
            // 简单估算：假设小兵平均分配给所有建筑
            const estimatedMinionsPerBuilding = Math.floor(actualMinionCount / this.buildings.length);
            building.currentMinions = Math.min(estimatedMinionsPerBuilding, building.maxMinions);
        });
    }
    
    // 渲染所有建筑
    render(ctx) {
        this.buildings.forEach(building => {
            building.render(ctx);
        });
    }
    
    // 获取建筑数量
    getBuildingCount() {
        return this.buildings.length;
    }
    
    // 获取建筑类型统计
    getBuildingStats() {
        const stats = {};
        this.buildings.forEach(building => {
            if (!stats[building.type]) {
                stats[building.type] = 0;
            }
            stats[building.type]++;
        });
        return stats;
    }
    
    // 重置建筑管理器
    reset() {
        this.buildings = [];
    }
    
    // 在指定位置添加默认建筑
    addDefaultBuildings() {
        // 在世界中心附近添加一些建筑
        const centerX = GAME_CONFIG.WORLD_WIDTH / 2;
        const centerY = GAME_CONFIG.WORLD_HEIGHT / 2;
        
        // 添加兵营
        this.addBuilding(centerX - 200, centerY - 200, this.buildingTypes.BARRACKS);
        this.addBuilding(centerX + 200, centerY - 200, this.buildingTypes.BARRACKS);
        
        // 添加工厂
        this.addBuilding(centerX, centerY + 200, this.buildingTypes.FACTORY);
        
        console.log('添加了默认建筑配置');
    }
} 